import { defineStore } from 'pinia'
import {
  getMenuListById,
  getUserInfoById,
  getVerifyCode,
  reqAccountLogin,
  reqAccountLogoutById,
  reqSecCertification,
  reqUpdatePassword
} from '@/service/module/account'
import router from '@/router'
import { localCache } from '@/utils/cache'
import { MENULIST, PERMISSIONS, TOKEN, USER_INFO } from '@/global/constant'
import { mapMenusToRoutes } from '@/utils/map-menu'
import { useGlobalStore } from '@/store'

interface IToken {
  name?: string
  value?: string
}

interface IUserInfo {
  loginId: number
  headPortrait: string
  userName: string
}

interface IAccountState {
  isLogining: boolean
  codeUrl: string
  token: IToken
  userInfo: IUserInfo
  permissions: string[]
  menuList: any[]
}

const useAccountStore = defineStore('account', {
  state: (): IAccountState => ({
    isLogining: false, // 是否正在点击登录按钮
    codeUrl: '', // 验证码图片
    token: localCache.getCache(TOKEN) ?? {}, // token
    // headPortrait: localCache.getCache(USER_INFO).headPortrait ?? '', // 用户头像
    userInfo: localCache.getCache(USER_INFO) ?? [], // 用户基本信息
    permissions: localCache.getCache(PERMISSIONS) ?? [], // 用户权限
    menuList: localCache.getCache(MENULIST) ?? [] // 用户菜单列表
  }),
  actions: {
    // 获取验证码
    async getVerifyCodeAction() {
      const res = await getVerifyCode()
      this.codeUrl = res.data
    },

    // 用户登录
    async reqAccountLoginAction(info: any) {
      // 1.获取用户id和token信息
      const loginRes = await reqAccountLogin(info)
      const loginId = Number(loginRes.data.loginId)
      const token = {
        name: loginRes.data.tokenName,
        value: loginRes.data.tokenValue
      }
      this.token = token
      localCache.setCache(TOKEN, token)

      // 2.根据用户的loginId去请求基本信息
      const userInfoRes = await getUserInfoById(Number(loginId))
      const headPortrait = userInfoRes.data.headPortrait
      const userName = userInfoRes.data.userName
      const permissions = userInfoRes.data.permissions
      this.userInfo = { loginId, userName, headPortrait }
      this.permissions = permissions
      localCache.setCache(USER_INFO, this.userInfo)
      localCache.setCache(PERMISSIONS, permissions)

      // 3.根据用户的loginId去请求菜单数据
      const menusRes = await getMenuListById(Number(loginId))
      const menuList = menusRes.data
      this.menuList = menuList
      localCache.setCache(MENULIST, menuList)

      // 4.根据菜单动态添加路由
      mapMenusToRoutes(menuList)

      // 5.初始化数据
      useGlobalStore().loadInitialData()

      // 跳转到主页
      await router.push('/main')
    },

    // 退出登录
    async reqAccountLogoutAction(userId: number) {
      // 1.调用退出登录接口
      await reqAccountLogoutById(userId)
      // 2.清空本地缓存
      // 除了主题色其他都要清空：先保存主题色，用clearCache一键清空，再重新设置主题色
      const globalStore = useGlobalStore()
      globalStore.cleanLocalUserInfo()
      // 3.跳转到登录页
      await router.push('/login')
    },

    // 修改密码
    async reqUpdatePwdAction(info: any) {
      await reqUpdatePassword(info)
      const globalStore = useGlobalStore()
      globalStore.cleanLocalUserInfo()
      await router.push('/login')
    },

    // 二次认证
    reqSecCertificationAction(
      password: string,
      pageName: string,
      btnType: string,
      skuType: number = -1
    ) {
      return new Promise((resolve) => {
        reqSecCertification(password, pageName, btnType, skuType).then(() => {
          resolve('成功')
        })
      })
    }
  }
})

export default useAccountStore
